package com.qf.chinatelcom.smsatragety.service.impl;

import com.qf.chinatelcom.smsatragety.cache.FilterOrderCache;
import com.qf.chinatelcom.smsatragety.filter.DuTyFilter;
import com.qf.chinatelcom.smsatragety.service.SmsManagerService;
import com.qianfeng.smsplatform.common.constants.RabbitMqConsants;
import com.qianfeng.smsplatform.common.model.Standard_Report;
import com.qianfeng.smsplatform.common.model.Standard_Submit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RefreshScope//刷新域，只有当加上这个注解的时候，去刷新那麽缓存才会自动刷新
public class SmsManagerServiceImpl implements SmsManagerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsManagerServiceImpl.class);

    private RabbitTemplate rabbitTemplate;

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    private FilterOrderCache filterOrderCache;

    @Autowired
    public void setFilterOrderCache(FilterOrderCache filterOrderCache) {
        this.filterOrderCache = filterOrderCache;
    }

    private Map<String, DuTyFilter> dutyFilterMap;

    @Autowired
    public void setDutyFilterMap(Map<String, DuTyFilter> dutyFilterMap) {
        //spring给我们注入了一个map里边放着职责过滤器
        this.dutyFilterMap = dutyFilterMap;
    }

    @Override
    public void deal(Standard_Submit submit) {
        //处理短信业务的模块

        List<String> filterOrderList = filterOrderCache.getFilterOrderList();//从缓存中获取到所有的数据
        for (String filterOrder : filterOrderList) {
            DuTyFilter duTyFilter = dutyFilterMap.get(filterOrder);//获取到对应的指责过滤器
            if (duTyFilter != null) {
                boolean sms = duTyFilter.dealSms(submit);//执行指责过滤器
                if(!sms){
                    LOGGER.error("过滤器{}拦截请求了", duTyFilter);
                    //通知客户结果，并且把结果写入到日志中
                    Standard_Report report = new Standard_Report();
                    report.setDescription(submit.getDescription());
                    report.setClientID(submit.getClientID());
                    report.setMobile(submit.getDestMobile());
                    report.setErrorCode(submit.getErrorCode());
                    report.setMsgId(submit.getMsgid());
                    report.setSendCount(1);//发送的次数，因为我们有可能无法一次性直接告诉客户结果
                    report.setSrcID(submit.getSrcSequenceId());
                    rabbitTemplate.convertAndSend(RabbitMqConsants.TOPIC_PUSH_SMS_REPORT,report);

                    return;
                }
            }
        }

    }
}
